# -*- coding:utf-8 -*-
import sys
reload(sys) 
sys.setdefaultencoding( "utf-8" ) 
import json
from decimal import Decimal
import MySQLdb
import time
def default(obj):
    if isinstance(obj, Decimal):
        return str(obj)
    raise TypeError
#连接数据库
dbstr=sys.argv[1]
city=sys.argv[2]
tbl = 'house_sell_pic'
print dbstr
#conn=MySQLdb.connect(host='rds1tu038044m8zub4o7.mysql.rds.aliyuncs.com',user='zhuge',passwd='zhuge1116',db=dbstr,port=3306,charset="utf8")
#conn=MySQLdb.connect(host='182.92.96.120',user='zhugef_offline',passwd='2d573c729a&^%460adc4c5547ff7e7%8',db=dbstr,port=3306,charset="utf8")
conn=MySQLdb.connect(host='101.200.122.53',user='zhugef_online',passwd='emd3ZW56*$FuYmFanVuZmVuZw%db',db=dbstr,port=3307,charset="utf8")
cur = conn.cursor()
cur.execute('select count(*) from %s'% tbl)
#获取数据库中记录总条数
count_all=cur.fetchone()[0]
print count_all
#每一次获取1000条数据
page_count=1000;
cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
#打开文件，准备写
filename = "%s/%s" % (city, tbl)
file = open(filename, "w")
#for($i=0;$i<=($sell_gov_count/$page_count);$i++)
j=0
phonelist=[]
page_num =  count_all/page_count + 1
 
for i in range(0, page_num):
    time.sleep(0.1)
    print 'i=',i
    try:
        query = "select pic_source_url from %s where pic_source_url like '%upfiles%' limit %d,%d"%(tbl,i*page_count,page_count)
        print 'query=', query
        cur.execute(query)
    except Exception as e:
        time.sleep(5)
        print 'exception=', e
        conn=MySQLdb.connect(host='101.200.122.53',user='zhugef_online',passwd='emd3ZW56*$FuYmFanVuZmVuZw%db',db=dbstr,port=3307,charset="utf8")
        cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
        print 'query=', query
        cur.execute(query)
    results=cur.fetchall()
    for row in results:
        j = j+1
	#print row
	print row['pic_source_url']
	if (row['pic_source_url'] != ""):
	    #phonelist.append(row['phone'])
		file.write(row['pic_source_url'])
		file.write("\n")
#file.write(json.dumps(phonelist,default=default))
file.close()
